package com.zsr.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @Author zsr
 * @Desc Spring boot 添加支持 Servlet 功能
 * @Date 2021/5/16 15:57
 */
@Configuration
public class DruidConfig {

    //将 yaml配置中写入
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

    //后台监控 web.xml
    //因为springboot内置了servlet容器所以没有web.xml,替代方法:ServletRegistrationBean
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean =
                new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        //后台需要有人登录，账号密码配置
        // druid/login.html登录进去的账号和密码
        HashMap<String,String> initParameters =new HashMap<>();
        initParameters.put("loginUsername","admin");//登录key是固定的loginUsername loginPassword
        initParameters.put("loginPassword","123");
        //允许谁可以访问
        initParameters.put("allow","");
        //禁止谁能访问initParameters.put("sun","127.0.0.1");

        bean.setInitParameters(initParameters);//设置初始话参数
        return bean;
    }


    // filter
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        
        //可以过滤哪些请求呢？
        HashMap<String, String> initParameters = new HashMap<>();

        //这些东西不进行统计
        initParameters.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParameters);
        return bean;

    }

}
